﻿package net.wangit.jdbc.executable;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DBImplementor;
import net.wangit.jdbc.JDBCException;
import net.wangit.jdbc.database.Database;
import net.wangit.jdbc.table.Column;
import net.wangit.jdbc.util.JDBCExceptionReporter;
import net.wangit.util.Checker;


/**
 * 数据库约束检查
 * 
 * @author watson
 * 
 */
public class ConstraintChecker {

	public ConstraintChecker() {
	}

	/**
	 * 是否重复记录
	 * 
	 * @param db
	 * @param tableName
	 * @param primaryKeyColumns
	 * @param row
	 * @return
	 * @throws JDBCException
	 */
	public static boolean isDuplicate(DBImplementor db, String tableName,
			List<Column> primaryKeyColumns, ColumnRow row) throws JDBCException {
		String sql = toPKSelectStatement(tableName, primaryKeyColumns);
		java.sql.PreparedStatement st;
		ResultSet rs;
		Database database = db.getJDBCSettings().getDatabase();
		try {
			st = db.getBatcher().prepareQueryStatement(sql, false);
			for (int i = 0; i < primaryKeyColumns.size(); i++) {
				Column column = primaryKeyColumns.get(i);
				String value = row.get(column.getName());
				column.getSqlType(database).set(st, value, i + 1);
			}

			rs = null;
			boolean flag;
			try {
				rs = db.getBatcher().getResultSet(st);
				flag = rs != null && rs.next();
			} catch (SQLException sqle) {
				JDBCExceptionReporter.logExceptions(sqle);
				throw new JDBCException("query error", sqle);
			} finally {
				db.getBatcher().closeQueryStatement(st, rs);
			}
			return flag;
		} catch (SQLException sqle) {
			JDBCExceptionReporter.logExceptions(sqle);
			throw new JDBCException("Cound't get prepareStatement", sqle);
		}
	}

	private static String toPKSelectStatement(String tableName,
			List<Column> primaryKeyColumns) {
		StringBuffer buf = new StringBuffer("select 1 from ");
		buf.append(tableName).append(" where ");
		Iterator<Column> iter = primaryKeyColumns.iterator();
		while (iter.hasNext()) {
			Column column = iter.next();
			buf.append(column.getName()).append("=?");
			if (iter.hasNext()) {
				buf.append(" and ");
			}
		}

		return buf.toString();
	}
	/**
	 * 生成异常信息
	 * @param primaryKeyColumns
	 * @param row
	 * @param unitId
	 * @return
	 */
	public static String getConstraintExceptionMessage(
			List<Column> primaryKeyColumns, AbstractColumnRow row, String unitId) {
		StringBuffer message = new StringBuffer();
		if (!Checker.isEmpty(unitId)) {
			message.append(unitId).append(",").append(row.getRowIndex());
			for (int i = 0; i < primaryKeyColumns.size(); i++) {
				message.append(",").append(primaryKeyColumns.get(i).getName());
			}

		} else {
			message.append(" (");
			for (int i = 0; i < primaryKeyColumns.size(); i++) {
				String columnName = primaryKeyColumns.get(i).getName();
				message.append(row.get(columnName));
				if (i < primaryKeyColumns.size() - 1) {
					message.append("/");
				}
			}

			message.append(")");
		}
		return message.toString();
	}
}
